/******************************************************************************
 *****************************************************************************/
#include "lpc210x.h"
#include "config.h"
#include "uart.h"
#include <stdlib.h>

// KM2103 LED on P0.13 (active high)
#define LEDPIN  13

void gpioInit(void)
{
	GPIO_IOSET  = (1<<LEDPIN);	// set Bit = LED off (active low)
	GPIO_IODIR |= (1<<LEDPIN);	// define LED-Pin as output
}

void ledToggle(void)
{
	static unsigned char state=0;

	state = !state;
	if (state) GPIO_IOCLR = (1<<LEDPIN);	// set Bit = LED on
	else GPIO_IOSET = (1<<LEDPIN);	// set Bit = LED off (active low)
}

void print_digit(unsigned int digit)
{
     switch (digit) {
     	case 0:
     			uart0Putch('0');
     	 break;
     	case 1:
     			uart0Putch('1');
     	 break;
     	case 2:
     			uart0Putch('2');
     	 break;
     	case 3:
     			uart0Putch('3');
     	 break;
     	case 4:
     			uart0Putch('4');
     	 break;
     	case 5:
     			uart0Putch('5');
     	 break;
     	case 6:
     			uart0Putch('6');
     	 break;
     	case 7:
     			uart0Putch('7');
     	 break;
     	case 8:
     			uart0Putch('8');
     	 break;
     	case 9:
     			uart0Putch('9');
     	 break;
	 }
}

void print_interger (unsigned int value)
{
	unsigned int digit;
	char number [11];
	int count = 0;
	int i;
	while (value!=0)
	{
        digit = value % 10;
        value = value / 10;
        number[count] = digit;
        count++;
        // print_digit (digit);
	}
	for (count--; count>=0; count--) {
		print_digit(number[count]);
    }

    uart0Puts("\r\n");
}

int main(void)
{
	int ch;

	systemInit();
	gpioInit();

	uart0Init(UART_BAUD(115200), UART_8N1, UART_FIFO_8); // setup the UART

	uart0Putch('M');

	uart0Puts("\r\nHello from KM2103!\r\n");
	uart0Puts("Press anykey to toggle the LED\r\n");

	ledToggle();

    print_interger (4294967296);

	while(1) {
		if ((ch = uart0Getch()) >= 0) {
			uart0Puts("You pressed : ");
			uart0Putch(ch);
			uart0Puts("\r\n");
			ledToggle();
		}
	}

	return 0;
}
